// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {
    
    // LIFE-CYCLE CALLBACKS:

    @property(cc.Vec2)
    direction = null;

    @property('number')
    speed: number = 3;

    onLoad () {
        // this.node.on('mousedown', this.onChangeHandler, this)
        cc.systemEvent.on('keydown', this.onChangeHandler, this);
    }

    start () {
        cc.log('start')
    }

    onChangeHandler(e: cc.Event.EventKeyboard){
        console.log(e.keyCode, cc.macro.KEY.left)
        switch(e.keyCode){
            case cc.macro.KEY.left:{
                this.direction = cc.v2(-1, 0)
                break;
            }
            case cc.macro.KEY.right:{
                this.direction = cc.v2(1, 0)

                break;
            }
            case cc.macro.KEY.up:{
                this.direction = cc.v2(0, 1)
                break;
            }
            case cc.macro.KEY.down:{
                this.direction = cc.v2(0, -1)
                break;
            }
            case cc.macro.KEY.left:{
                this.direction = null;
                break;
            }
            default : {
                this.direction = null;
            }
        }
    }

    update (dt) {
        if(this.direction === null) return;
        let pos: cc.Vec2 = this.node.getPosition();
        pos.x += this.speed * this.direction.x;
        pos.y += this.speed * this.direction.y;

        this.node.setPosition(pos);
    }
}
